// src/stores/station.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  Station, 
  StationDetail, 
  StationListResponse,
  StationStatus
} from '@/types/station'

export const useStationsStore = defineStore('stations', () => {
  // 状态
  const stations = ref<Station[]>([])
  const selectedStation = ref<Station | null>(null)
  const stationDetail = ref<StationDetail | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const userLocation = ref<[number, number]>([103.975038, 30.756089]) // 默认位置：第一个充电站位置

  // 计算属性 - 状态映射
  const getStationStatus = (station: Station): StationStatus => {
    // 根据赛方数据：stationStatus 50 表示正常运营
    if (station.stationStatus !== 50 || station.openStatus !== 1) {
      return 'maintenance'
    }
    
    const totalAvailable = station.quickAvailableNum + station.slowAvailableNum
    const totalCount = station.quickChargeNum + station.slowChargeNum
    
    if (totalCount === 0) return 'maintenance'
    
    const ratio = totalAvailable / totalCount
    if (ratio > 0.7) return 'free'
    else if (ratio > 0) return 'busy'  // 修改逻辑：只要有一个可用，就显示为繁忙状态
    else return 'maintenance'  // 完全没有可用时才显示为维护状态
  }

  const getAvailableCount = (station: Station): number => {
    return station.quickAvailableNum + station.slowAvailableNum
  }

  const getTotalCount = (station: Station): number => {
    return station.quickChargeNum + station.slowChargeNum
  }

  // 格式化距离显示
  const formatDistance = (distance: number): string => {
    if (distance < 1000) {
      return `${Math.round(distance)}米`
    } else {
      return `${(distance / 1000).toFixed(1)}公里`
    }
  }

  // 模拟网络延迟
  const simulateNetworkDelay = () => new Promise(resolve => 
    setTimeout(resolve, Math.random() * 500 + 200)
  )

  // 设置用户位置
  const setUserLocation = (lng: number, lat: number) => {
    userLocation.value = [lng, lat]
    updateStationsDistance()
  }

  // 加载充电站列表数据
  const loadStations = async () => {
    loading.value = true
    error.value = null
    try {
      await simulateNetworkDelay()
      
      const response = await fetch('/mockStations.json')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data: StationListResponse = await response.json()
      stations.value = data.stationList
      
      // 更新距离信息
      updateStationsDistance()
      
      console.log(`✅ 成功加载 ${stations.value.length} 个充电站`)
    } catch (err) {
      error.value = '加载充电站数据失败'
      console.error('加载数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 加载站点详情数据
  const loadStationDetail = async (_stationId: string): Promise<StationDetail | null> => {
    loading.value = true
    try {
      await simulateNetworkDelay()
      
      // 模拟从API加载详情数据
      const response = await fetch('/mockStationDetail.json')
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const detail: StationDetail = await response.json()
      stationDetail.value = detail
      return detail
    } catch (err) {
      console.error('加载站点详情失败:', err)
      return null
    } finally {
      loading.value = false
    }
  }

  // 计算两点之间的距离（简单球面距离计算）
  const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
    const R = 6371000 // 地球半径（米）
    const dLat = (lat2 - lat1) * Math.PI / 180
    const dLon = (lon2 - lon1) * Math.PI / 180
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
      Math.sin(dLon/2) * Math.sin(dLon/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    const distance = R * c
    return Math.round(distance)
  }

  // 更新所有充电站的距离
  const updateStationsDistance = () => {
    stations.value.forEach(station => {
      const distance = calculateDistance(
        userLocation.value[1], 
        userLocation.value[0], 
        station.lat, 
        station.lng
      )
      station.distance = distance
    })
    
    // 按距离排序
    stations.value.sort((a, b) => a.distance - b.distance)
  }

  const setSelectedStation = (station: Station | null) => {
    selectedStation.value = station
    if (station) {
      loadStationDetail(station.stationId)
    } else {
      stationDetail.value = null
    }
  }

  // 搜索充电站
  const searchStations = (keyword: string) => {
    if (!keyword) return stations.value
    return stations.value.filter(station => 
      station.stationName.toLowerCase().includes(keyword.toLowerCase()) ||
      station.address.toLowerCase().includes(keyword.toLowerCase()) ||
      station.brandName.toLowerCase().includes(keyword.toLowerCase())
    )
  }

  // 按状态筛选
  const getStationsByStatus = (status: StationStatus) => {
    return stations.value.filter(station => getStationStatus(station) === status)
  }

  // 获取品牌列表
  const getBrandList = computed(() => {
    const brands = new Set(stations.value.map(station => station.brandName))
    return Array.from(brands)
  })

  return {
    // 状态
    stations,
    selectedStation,
    stationDetail,
    loading,
    error,
    userLocation,
    
    // 计算属性
    freeStations: computed(() => getStationsByStatus('free')),
    busyStations: computed(() => getStationsByStatus('busy')),
    maintenanceStations: computed(() => getStationsByStatus('maintenance')),
    getBrandList,
    
    // 方法
    loadStations,
    loadStationDetail,
    setSelectedStation,
    setUserLocation,
    searchStations,
    updateStationsDistance,
    
    // 工具方法
    getStationStatus,
    getAvailableCount,
    getTotalCount,
    formatDistance
  }
})